package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdUserImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        if(dto!=null&& StringUtils.isNotBlank(dto.getName())&&StringUtils.isNotBlank(dto.getPassword())){
            List<AdUser> adUserList = this.list();
            for (AdUser adUser : adUserList) {
                if(adUser.getName().equals(dto.getName())){
                    String salt = adUser.getSalt();
                    String pswd = dto.getPassword();
                    pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
                    if(adUser.getPassword().equals(pswd)){
                        Map<String,Object> map  = new HashMap<>();
                        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                        adUser.setSalt("");
                        adUser.setPassword("");
                        map.put("user",adUser);
                        return ResponseResult.okResult(map);
                    }
                }
            }
            return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
    }
}
